package mapred.example.model;

import java.util.ArrayList;
import java.util.List;

import util.FieldUtil;

public class Anchors {

    List<Anchor> anchors = new ArrayList<Anchor>();

    public Anchors(String anchorStr) {
        for (String a : anchorStr.split("\1")) {
            if (!a.isEmpty()) {
                anchors.add(new Anchor(a));
            }
        }
    }

    public List<Anchor> getAnchors() {
        return anchors;
    }

    public String getStr() {
        StringBuilder sb = new StringBuilder();
        for (Anchor anchor : anchors) {
            sb.append("\1");
            sb.append(anchor.getStr());
        }
        if (sb.length() == 0) {
            return "";
        } else {
            return sb.substring(1);
        }
    }

    public String toRLV(String[] query) {
        StringBuilder sb = new StringBuilder();
        sb.append(this.getLength());
        for (String q : query) {
            sb.append("\t");
            sb.append(q);
            sb.append(" ");
            sb.append(this.getTF(q));
        }
        for (Anchor anchor : anchors) {
            sb.append(anchor.toRLV(query));
        }
        return sb.toString();
    }

    private long getTF(String q) {
        long sum = 0;
        for (Anchor anchor : anchors) {
            sum += FieldUtil.getPositions(anchor.getText(), q).size();
        }
        return sum;
    }

    private long getLength() {
        long len = 0;
        for (Anchor anchor : anchors) {
            len += anchor.getLength();
        }
        return len;
    }

}
